package reflect;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URISyntaxException;


/**
 * 自动调用和当前类在同一个包中的类的方法
 * 方法要求名字含有S且参数个数为0
 */
public class reflectDemo8 {
    public static void main(String[] args) throws URISyntaxException, ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException {
        File dir=new File(reflectDemo8.class.getResource(".").toURI());

        System.out.println(dir.getAbsolutePath());//D:\IdeaProjects\JSD2109_SE\target\classes\reflect

        //获取所有的class文件
        File[] subs=dir.listFiles(f->f.getName().endsWith(".class"));
        for (File file : subs) {
            String fileName = file.getName();
            String className = fileName.substring(0, fileName.indexOf("."));
            Class cls = Class.forName("reflect." + className);
            Object o = cls.newInstance();
            Method[] methods = cls.getDeclaredMethods();
            for (Method method : methods) {
                String methodName = method.getName();
                //名字含有S 并且参数的个数为0
                if (methodName.toLowerCase().contains("s") && method.getParameterCount() == 0) {
                    System.out.println("自动调用方法:" + methodName + "()");
                    method.invoke(o);
                }
            }


        }

    }

}
